package com.huzz.security.filter;

import com.huzz.domain.Payload;
import com.huzz.entity.SysUser;
import com.huzz.properties.Properties;
import com.huzz.util.JwtUtil;
import com.huzz.util.ResponseUtils;
import com.huzz.util.SpringUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.joda.time.DateTime;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class JwtVerificationFilter extends BasicAuthenticationFilter {

    /**
     * 配置信息
     */
    private Properties properties;


    public JwtVerificationFilter(AuthenticationManager authenticationManager, Properties properties) {
        super(authenticationManager);
        this.properties = properties;
    }

    /**
     * 拦截认证
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            String header = request.getHeader("Authorization");
            if (header == null || !header.startsWith("Bearer ")) {
                chain.doFilter(request, response);
                return;
            } else {
                //如果token的格式正确，则先要获取到token
                String token = header.replace("Bearer ", "");
                //使用公钥进行解密然后来验证token是否正确
                Payload<SysUser> payload = JwtUtil.getInfoFromToken(token, properties.getPublicKey(), SysUser.class);
                // 不使用缓存: 验证是否退出登录 / 使用缓存: 验证token是否过期
                if (!validationExpire(payload)) {
                    ResponseUtils.write(response, HttpServletResponse.SC_FORBIDDEN, "登录令牌已失效, 请重新登录！");
                    logger.info("登录令牌已失效, 请重新登录！");
                    return;
                }
                // 验证成功
                SysUser sysUser = payload.getUserInfo();
                if (sysUser != null) {
                    // 解析成功, 验证权限
                    UsernamePasswordAuthenticationToken authResult = new UsernamePasswordAuthenticationToken(sysUser.getUsername(), null, sysUser.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authResult);
                    chain.doFilter(request, response);
                } else {
                    ResponseUtils.write(response, HttpServletResponse.SC_FORBIDDEN, "用户验证失败！");
                }
            }
        } catch (ExpiredJwtException e) {
            ResponseUtils.write(response, HttpServletResponse.SC_FORBIDDEN, "请您重新登录！");
        }

    }

    /**
     * Token过期验证
     *
     * @param payload
     * @return
     */
    private boolean validationExpire(Payload<SysUser> payload) {
        RedisTemplate redisTemplate = SpringUtils.getBean("redisTemplate");

        String userKey = payload.getId();
        if (userKey == null) {
            return false;
        }
        // 过期, 认证失败
        Payload<SysUser> body = (Payload<SysUser>) redisTemplate.opsForValue().get(userKey);
        if (body == null) {
            return false;
        }
        // 不使用缓存过期策略
        if (!properties.isOnCacheToken()) {
            return true;
        }
        // 这里存入过期时间是为了判断客户端和认证服务端开启缓存是否保持一致. 因为使用缓存时, token中解析不出过期时间
        int expire = properties.getExpireLifeExt();
        payload.setExpiration(DateTime.now().plusMinutes(expire).toDate());
        // 未过期
        long expireTime = body.getExpiration().getTime();
        long currentTime = System.currentTimeMillis();
        // 剩余过期时间 <= 2分钟时, 执行刷新token
        long timeLeft = expireTime - currentTime;
        if (timeLeft <= 2 * 60 * 1000L) {
            redisTemplate.opsForValue().set(userKey, payload, expire, TimeUnit.MINUTES);
            logger.info("Token过期时间已刷新");
        }

        return true;
    }
}